import copy

__author__ = 'st316'
'''
Given a set of distinct integers, S, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
'''


class Solution:
    # @param S, a list of integer
    # @return a list of lists of integer
    def subsets(self, S):
        if len(S) == 0:
            return []
        if len(S) == 1:
            return [[], [S[0]]]
        tmp1 = self.subsets(S[:-1])
        tmp2 = copy.deepcopy(tmp1)
        for x in tmp2:
            self.insert(x, S[-1])
        return tmp1 + tmp2

    def insert(self, l, t):
        if len(l) == 0:
            l.append(t)
            return
        low = 0
        high = len(l) - 1
        mid = 0
        while low <= high:
            mid = (low + high) / 2
            if l[mid] < t:
                low = mid + 1
            elif l[mid] > t:
                high = mid - 1
        if low == mid + 1:
            l.insert(mid + 1, t)
        elif high == mid - 1:
            l.insert(mid, t)


if __name__ == '__main__':
    s = Solution()
    m = [4, 0, 1]
    print s.subsets(m)